clear all
set more off
tempfile ubigeo

/*

This dofile pulls in raw ENAHO data from the individual module (200) and saves the outcome (200.dta) in the "working" directory

Important: the variable ubigeo refers to district of residence and it is harmonized to reflect the 1993 version of the code. 
Same principle applies to ubigeonac, which is the ubigeo at birth. In the dofile this is harmonized by pulling in the files:

ubiequivalence`y'to1993.dta, and
ubigeonac`y'to1993.dta

where the index `y' refers to the specific year of the survey that has been harmonized to the 1993 version of the ubigeo code.
see the series of dofiles within the "ubigeo" directory within the "dofiles" directory.


*/


** PATHS
local data ../data/enaho
local working ../working

**** 2004-2016
forvalues y = 2004/2016 {
	use `data'/`y'/200, clear

	recode p209 (1 2 = 1) (3 4 5 6 = 0) (else = .), gen(married)
	recode p203 (1 = 1) (0 2/12 = 0) (else = .), gen(head)
	
	gen ubigeo`y' = real(ubigeo)
	merge m:1 ubigeo`y' using `data'/`y'/ubiequivalence`y'to1993
	drop if _merge == 2
	drop _merge
	
	cap destring p208a2, replace
	gen ubigeonac`y' = p208a2 if p208a1 == 0
	merge m:1 ubigeonac`y' using `data'/`y'/ubigeonac`y'to1993
	drop if _merge == 2
	drop _merge
	
	gen foreignborn = ubigeonac1993 == . & p208a1 == 0
	replace ubigeonac1993 = ubigeo1993 if ubigeonac1993 == . & p208a1 == 1
	
	gen age = p208a
	gen age2 = age ^ 2
	recode p207 (2 = 0), gen(male)
	recode estrato (6 7 8  = 1) (1/5 = 0), gen(rural)

	gen weight = facpob07
	keep if age >= 16
	
	destring conglome vivienda hogar codperso, replace
	keep conglome vivienda hogar codperso age* married male head rural ubigeo1993 ubigeonac1993 foreignborn weight
	
	gen year = `y'
	save `working'/200_`y', replace
}

use `working'/200_2004, clear
forvalues y = 2005/2016 {
	append using `working'/200_`y'
}	

forvalues y = 2004/2016 {
	erase `working'/200_`y'.dta
}	

gen provnac1993 = int(ubigeonac1993 / 100)
** SAVE
save `working'/200, replace
